package com.lin.auth.common.config;

import cn.dev33.satoken.util.SaResult;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;

@ControllerAdvice // 标记为全局异常处理类
public class GlobalExceptionHandler {

    // 处理所有未捕获的异常
    @ExceptionHandler(Exception.class)
    public ResponseEntity<SaResult> handleGlobalException(Exception ex, WebRequest request) {
        SaResult errorResponse = new SaResult(
                HttpStatus.INTERNAL_SERVER_ERROR.value(),
                ex.getMessage(),
                request.getDescription(false)
        );
        return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    // 处理自定义的业务异常
    @ExceptionHandler(CustomBusinessException.class)
    public ResponseEntity<SaResult> handleCustomBusinessException(CustomBusinessException ex, WebRequest request) {
        SaResult errorResponse = new SaResult(
                ex.getStatus().value(),
                ex.getMessage(),
                request.getDescription(false)
        );
        return new ResponseEntity<>(errorResponse, ex.getStatus());
    }
}